<template>
  <div class="release_wrap">
    <div class="release_title">播 放 视 频</div>
    <el-card class="release_card">
      <el-button type="primary" round icon="el-icon-arrow-left" style="margin-bottom: 40px"
        @click="jump_home">返回首页</el-button>

      <el-table stripe :data="tableData" style="width: 100%" height="600px">
        <el-table-column prop="videoName" label="视频名称" min-width="280">
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="primary" @click="playVideo(scope.$index, scope.row)">播放</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog :modal="false" title="视频播放" v-model="dialogVisible" width="40%">
      <p class="video_title">{{ videoName }}</p>
      <video :src="videoUrl" controls width="100%" @canplay="getVidDur()" id="myvideo"></video>
    </el-dialog>
  </div>
</template>


<script>
import { ref, onMounted } from 'vue';
// import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import axios from 'axios';
// import IPconfig from './IPconfig';

const baseUrl = 'http://localhost:8080';

export default {
  setup() {
    // const store = useStore();
    const router = useRouter();

    const title = ref("");
    const videolist = ref("");
    const tableData = ref([]);
    const dialogVisible = ref(false);
    const videoId = ref(0);
    const videoName = ref('');
    const videoUrl = ref('');

    const getVidDur = () => {
      const videoTime = document.getElementById("myvideo");
      console.log(videoTime.duration); // 获取视频时长
      console.log(videoTime.currentTime); // 获取视频当前播放时间
    };

    const jump_home = () => {
      router.replace('/');
    };

    // 获取video表格数据
    const getVideoInfo = async () => {
      try {
        const response = await axios.get(baseUrl + "/SelectVideo/table");
        tableData.value = response.data;
      } catch (error) {
        console.error('Error fetching video info:', error);
      }
    };

    // 点击播放按钮
    const playVideo = async (i, val) => {
      dialogVisible.value = true;
      videoName.value = val.videoName;
      videoId.value = val.id;

      try {
        // 发送HEAD请求获取视频的总大小
        const sizeResponse = await axios.get(`${baseUrl}/SelectVideo/getVideoSizeById/${videoId.value}`);
        const totalSize = sizeResponse.data;
        const chunkSize = Math.ceil(totalSize / 20); // 设置分片大小为总大小的1/5

        // 定义分片传输的函数
        const loadVideoChunk = async (startByte, endByte) => {
          const response = await axios.get(`${baseUrl}/SelectVideo/policemen/${videoId.value}`, {
            headers: {
              Range: `bytes=${startByte}-${endByte}`
            },
            responseType: 'blob'
          });
          return response.data;
        };

        // 获取所有分片的Promise
        const chunkPromises = [];
        for (let i = 0; i < 20; i++) {
          const startByte = i * chunkSize;
          const endByte = Math.min(startByte + chunkSize - 1, totalSize - 1);
          chunkPromises.push(loadVideoChunk(startByte, endByte));
        }

        // 执行所有分片请求，并在全部请求完成后开始播放视频
        const chunks = await Promise.all(chunkPromises);
        const videoBlob = new Blob(chunks);
        videoUrl.value = URL.createObjectURL(videoBlob);
      } catch (error) {
        console.error('Error loading video:', error);
      }
    };

    // 生命周期钩子
    onMounted(() => {
      getVideoInfo();
    });

    return {
      title,
      videolist,
      tableData,
      dialogVisible,
      videoId,
      videoName,
      videoUrl,
      jump_home,
      getVidDur,
      playVideo,
      getVideoInfo,
      // article: store.state.article
    };
  }
};
</script>

<style scoped>
.release_wrap {
  padding: 20px;
}

.release_title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
}

.release_card {
  margin-top: 20px;
}

.video_title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}
</style>